
package com.yesep.learn.mqtt.server.broker.handler.protocol;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yesep.learn.mqtt.protocol.IPubRec;
import com.yesep.learn.mqtt.server.common.Constants;
import com.yesep.learn.mqtt.server.common.message.DupPubRelMessageStore;
import com.yesep.learn.mqtt.server.common.message.IDupPubRelMessageStoreService;
import com.yesep.learn.mqtt.server.common.message.IDupPublishMessageStoreService;
import com.yesep.learn.mqtt.util.ChannelUtil;

import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.MqttFixedHeader;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageFactory;
import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.netty.util.AttributeKey;

/**
   *   消息编号：5
 * @Description: PUBREC连接处理，发布已接收，保证传递1
 */
@Service
public class PubRec implements IPubRec {

	private static final Logger LOGGER = LoggerFactory.getLogger(PubRel.class);
	@Autowired
	private IDupPublishMessageStoreService dupPublishMessageStoreService;
	@Autowired
	private IDupPubRelMessageStoreService dupPubRelMessageStoreService;

	public void process(Channel channel, MqttMessage msg) {
		MqttMessageIdVariableHeader variableHeader = (MqttMessageIdVariableHeader) msg.variableHeader();
		int messageId = variableHeader.messageId();
		String clientId = ChannelUtil.getClientId(channel);
		MqttMessage pubRelMessage = MqttMessageFactory.newMessage(new MqttFixedHeader(MqttMessageType.PUBREL, false, MqttQoS.AT_MOST_ONCE, false, 0), MqttMessageIdVariableHeader.from(messageId), null);
		LOGGER.debug("PUBREC - clientId: {}, messageId: {}", clientId, messageId);
		dupPublishMessageStoreService.remove(clientId, messageId);
		DupPubRelMessageStore dupPubRelMessageStore = new DupPubRelMessageStore().setClientId(clientId).setMessageId(messageId);
		dupPubRelMessageStoreService.put(clientId, dupPubRelMessageStore);
		channel.writeAndFlush(pubRelMessage);
	}

}
